package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
	"video_demo/entity"
	"video_demo/result"
	"video_demo/service/topic_service"
	"video_demo/vo"
)

func SaveSingleQuestion(c *gin.Context) {
	var req entity.Topic
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(http.StatusInternalServerError, "无效的请求格式: "+err.Error()))
		return
	}

	err := topic_service.SaveSingleQuestion(&req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.Success("保存成功", ""))
}

func GetAllTopic(c *gin.Context) {
	var filter vo.TopicFilter
	if err := c.ShouldBindQuery(&filter); err != nil {
		c.JSON(http.StatusBadRequest, result.Fail(400, "参数格式错误"))
		return
	}
	topics, err := topic_service.GetAllTopic(filter)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.Success("查询成功", topics))
}

func UploadQuestionFile(c *gin.Context) {
	file, fileHeader, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, result.Fail(400, "文件上传失败: "+err.Error()))
		return
	}
	fileExt := filepath.Ext(fileHeader.Filename)
	content, err := topic_service.UploadQuestionFile(file, fileExt)

	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, "解析失败 : "+err.Error()))
	}

	c.JSON(http.StatusOK, result.Success("解析成功", content))
}

func UploadBatchQuestion(c *gin.Context) {
	questions := c.PostForm("questions")
	fmt.Println("questions : ", questions)
	content, err := topic_service.UploadBatchQuestion(questions)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.Success("解析成功", content))
}

func SaveBatchQuestions(c *gin.Context) {
	var req struct {
		Questions []entity.Topic `json:"questions" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, result.Fail(400, "参数格式错误: "+err.Error()))
		return
	}
	err := topic_service.SaveBatchQuestions(req.Questions)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, "题目保存异常 : "+err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.Success("保存成功", ""))
}

func DeleteTopicByID(c *gin.Context) {
	id := c.PostForm("id")
	err := topic_service.DeleteTopicByID(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.Success("删除成功", ""))
}

func ChatMassge(c *gin.Context) {
	chatClient := entity.NewChatClient()

	var req entity.ChatRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, result.Fail(http.StatusBadRequest, "无效的请求格式: "+err.Error()))
		return
	}

	resp, err := topic_service.ChatCompletion(chatClient, c.Request.Context(), &req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(http.StatusInternalServerError, "聊天服务错误 : "+err.Error()))
		return
	}

	c.JSON(http.StatusOK, resp)
}

func GetAllTopicFilter(c *gin.Context) {
	var filter vo.QueryTopic
	if err := c.ShouldBind(&filter); err != nil {
		c.JSON(http.StatusBadRequest, result.Fail(400, "参数格式错误 : "+err.Error()))
		return
	}
	if filter.PageSize == 0 || filter.PageNum == 0 {
		c.JSON(http.StatusBadRequest, result.Fail(400, "分页数据错误"))
		return
	}

	topic, err := topic_service.GetAllTopicFilter(&filter)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, err.Error()))
		return
	}

	c.JSON(http.StatusOK, topic)
}

func CreateTestPaper(c *gin.Context) {
	var req vo.TestPaper
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, result.Fail(400, "参数格式错误 : "+err.Error()))
		return
	}

	id, err := topic_service.CreateTestPaper(&req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, "试卷保存失败 : "+err.Error()))
		return
	}
	// 发送 QuestionIds 到 channel
	select {
	case TestPaperChan <- TestPaperInfo{
		QuestionIDs: req.QuestionIds,
		ID:          id,
	}:
	default:
		c.JSON(http.StatusInternalServerError, result.Fail(500, "异步处理试卷失败"))
		return
	}

	c.JSON(http.StatusOK, result.Success("试卷保存成功", ""))
}

type TestPaperInfo struct {
	QuestionIDs []int64
	ID          int
}

var TestPaperChan = make(chan TestPaperInfo, 10) // 缓冲大小可根据并发需求调整

// 监听接口的响应码
func WithPostAction(callback func(TestPaperInfo), handler gin.HandlerFunc) gin.HandlerFunc {
	return func(c *gin.Context) {
		handler(c)

		if c.Writer.Status() == http.StatusOK {
			select {
			case info := <-TestPaperChan:
				go callback(info)
			default:
			}
		}
	}
}
func CreateTestPaperInfo(info TestPaperInfo) {
	err := topic_service.CreateTestPaperInfo(&info.QuestionIDs, info.ID)
	if err != nil {
		fmt.Printf("试卷处理失败: %v\n", err)
		return
	}
}

func GetTestPapers(c *gin.Context) {
	var filter vo.TestPaperFilter
	if err := c.ShouldBindJSON(&filter); err != nil {
		c.JSON(http.StatusBadRequest, result.Fail(400, "参数格式错误 : "+err.Error()))
		return
	}

	testPapers, err := topic_service.GetTestPapers(&filter)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, err.Error()))
		return
	}

	c.JSON(http.StatusOK, result.Success("查询成功", testPapers))
}

func DeleteTestPaper(c *gin.Context) {
	id := c.PostForm("id")
	err := topic_service.DeleteTestPaper(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, result.Fail(500, err.Error()))
	}
	c.JSON(http.StatusOK, result.Success("删除成功", nil))
}
